#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

class InetAddr
{
public:
    InetAddr() = default;

    //网络转主机
    InetAddr(struct sockaddr_in& addr)
        :_addr(addr)
    {
        SetAddr(addr);
    }

    //主机转网络
    InetAddr(const std::string& ip, uint16_t port)
        :_ip(ip)
        , _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        _addr.sin_port = htons(_port);
    }

    //主机转网络 -- 针对服务器进行任意地址绑定
    InetAddr(uint16_t port)
        :_ip("0")
        , _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = INADDR_ANY;
        _addr.sin_port = htons(_port);
    }

    void SetAddr(struct sockaddr_in& addr)
    {
        _port = ntohs(addr.sin_port);
        char buff[64] = {0};
        inet_ntop(AF_INET, &addr.sin_addr, buff, sizeof(buff));
        _ip = buff;
    }

    std::string IP() { return _ip; }
    uint16_t Port() { return _port; }
    const struct sockaddr_in& NetAddr() { return _addr; }
    const struct sockaddr* NetAddrPtr() {return (const struct sockaddr*)&_addr; }
    socklen_t AddrLen() { return sizeof(_addr); }
    bool operator==(const InetAddr &addr)
    {
        return addr._ip == _ip && addr._port == _port;
    }
    std::string StringAddr()
    {
        return _ip + ":" + std::to_string(_port);
    }
private:
    struct sockaddr_in _addr; // 网络socket
    std::string _ip;
    uint16_t _port;
};